//
//  IGPushiGalleryListVC.m
//  jingdongfang
//
//  Created by BOE on 2017/9/7.
//  Copyright © 2017年 BOE. All rights reserved.
//

#import "IGPushiGalleryListVC.h"
#import "IGiGalleryEqu.h"
#import "IGiGalleryListApi.h"
#import "IGiGalleryPushApi.h"
#import "IGIssueImageCell.h"
#import "IGAtlasDetailModel.h"
#import "IGPicturePushApi.h" //推送接口
#import "IGMultipleDrawingsBuyVC.h" //多图打包购买VC

static NSString *issueImageCellIdentifier = @"issueImageCellIdentifier";
@interface IGPushiGalleryListVC ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource,UIGestureRecognizerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIView *bottomView;
    
@property (nonatomic, strong) NSMutableArray *iGalleryListArr;
@property (nonatomic, strong) IGiGalleryListApi *api; //设备api

@property (nonatomic, assign) IGPushiGalleryType type;

@property (nonatomic, assign) BOOL isAllDeviceSelected;
@property (nonatomic, strong) UIImageView *allSelectedImageV;
@property (nonatomic, strong) IGPicturePushApi *pushApi; //推送接口
@property (nonatomic, copy) NSMutableString * deviceIds; //设备id，多了以英文逗号隔开
@property (nonatomic, copy) NSMutableString * pIds;//作品id、画单id，多个以英文逗号隔开，画单只能传一个画单id
@property (nonatomic, copy) NSString *unPurchaseId; // 未支付的作品id集合
    
@end

@implementation IGPushiGalleryListVC

- (instancetype)initWithType:(IGPushiGalleryType)type {
    self = [super init];
    if (self) {
        self.type = type;
        self.isAllDeviceSelected = NO;
        self.recommendArr = [NSArray array];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = NSLocalizedString(@"Select and Push Pictures to BOE-iGallery", nil);
    self.view.backgroundColor = [UIColor mainBackgroundColor];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-44);
    }];
    
    [self.view addSubview:self.bottomView];
    
    [self requestData];
    
}
    
- (void)requestData {
    self.api = [[IGiGalleryListApi alloc] initWithType:IGiGalleryListTypeSuccess];
    
    __weak typeof(self) weakSelf = self;
    [self.api startWithDecodeClass:[IGiGalleryListResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            IGiGalleryListResp *resp = responseObject;
            IGiGalleryListModel *model = resp.data;
            weakSelf.iGalleryListArr = [NSMutableArray arrayWithArray:model.equs];
            
            [weakSelf.tableView reloadData];
        }
    }];
}

#pragma mark -<UITableViewDelegate, UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.iGalleryListArr.count;
}
    
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"iGalleryListCellID";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    
    IGiGalleryEqu *equ = self.iGalleryListArr[indexPath.row];
    cell.textLabel.font = [UIFont font14];
    cell.textLabel.textColor = [UIColor c4Color];
    cell.textLabel.text = equ.title;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(0, 0, 22, 22)];
    button.userInteractionEnabled = NO;
    [button setImage:[UIImage imageNamed:@"pushiGallery_Normal"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"pushiGallery_Selected"] forState:UIControlStateSelected];
    button.selected = equ.isSelected;
    cell.accessoryView = button;
    
    return cell;
}
    
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    [self selButClick:indexPath];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *selectAllDeviceView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 50)];
    selectAllDeviceView.backgroundColor = [UIColor whiteColor];
    UILabel *allSelctLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 0, 40, 50)];
    allSelctLabel.text = NSLocalizedString(@"全选", nil);
    allSelctLabel.font = [UIFont font14];
    allSelctLabel.textColor = [UIColor c4Color];
    [selectAllDeviceView addSubview:allSelctLabel];
    
    UIImageView *allSelectImageView = [[UIImageView alloc]initWithFrame:CGRectMake(KSCREENWIDTH - 37, 14, 22, 22)];
    if (_isAllDeviceSelected) {
        [allSelectImageView setImage:[UIImage imageNamed:@"pushiGallery_Selected"]];
    } else   [allSelectImageView setImage:[UIImage imageNamed:@"pushiGallery_Normal"]];

    self.allSelectedImageV = allSelectImageView;
    [selectAllDeviceView addSubview:allSelectImageView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectAllDevice)];
    tap.delegate = self;
    [selectAllDeviceView addGestureRecognizer:tap];
    
    return selectAllDeviceView;
}

#pragma mark -UICollectionViewDelegate, UICollectionViewDataSource
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.recommendArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    IGIssueImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:issueImageCellIdentifier forIndexPath:indexPath];
    if ([self.source integerValue]==1) {
        IGAtlasDetailModel *atlastInfo=self.recommendArr[indexPath.item];
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:atlastInfo.image]];
    }
    IGArtWorkModel *info = self.recommendArr[indexPath.item];
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:info.image]];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)collectionViewLayout;
    CGFloat width = (self.collectionView.width - flowLayout.sectionInset.left - flowLayout.sectionInset.right - flowLayout.minimumLineSpacing * 3) / 4;
    return CGSizeMake(width, width);
}

#pragma mark - set && get
/*
- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, KSCREENHEIGHT-44, KSCREENWIDTH, 44)];
        if ([UIApplication sharedApplication].statusBarFrame.size.height!=20) {
            double viewY=KSCREENHEIGHT-44-[UIApplication sharedApplication].statusBarFrame.size.height/2;
            _bottomView.y =viewY;
        }
        UIButton *selButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [selButton setImage:[UIImage imageNamed:@"pushiGallery_Normal"] forState:UIControlStateNormal];
        [selButton setImage:[UIImage imageNamed:@"pushiGallery_Selected"] forState:UIControlStateSelected];
        //        [selButton setTitle:@"全选" forState:UIControlStateNormal];
        [selButton setTitle:NSLocalizedString(@"Select All", nil) forState:UIControlStateNormal];
        [selButton setTitleColor:[UIColor c4Color] forState:UIControlStateNormal];
        selButton.tag = 100;
        [selButton addTarget:self action:@selector(selButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        selButton.titleLabel.font = [UIFont font16];
        [_bottomView addSubview:selButton];
        
        UIButton *pushButton = [UIButton buttonWithType:UIButtonTypeCustom];
        //        [pushButton setTitle:@"推送" forState:UIControlStateNormal];
        [pushButton setTitle:NSLocalizedString(@"Push", nil) forState:UIControlStateNormal];
        pushButton.backgroundColor = [UIColor appColor];
        pushButton.titleLabel.font = [UIFont font16];
        [pushButton addTarget:self action:@selector(pushButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [pushButton setTitleColor:[UIColor c3Color] forState:UIControlStateNormal];
        [_bottomView addSubview:pushButton];
        
        [selButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.mas_equalTo(0);
            make.height.mas_equalTo(44);
            make.width.mas_equalTo(KSCREENWIDTH/3);
        }];
        
        [pushButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.bottom.mas_equalTo(0);
            make.height.mas_equalTo(44);
            make.width.mas_equalTo(KSCREENWIDTH*2/3);
        }];
    }
    return _bottomView;
}
*/

- (UIView *)bottomView {
    if (!_bottomView) {
        
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, KSCREENHEIGHT-44, KSCREENWIDTH, 44)];
        if ([UIApplication sharedApplication].statusBarFrame.size.height!=20) {
            double viewY=KSCREENHEIGHT-44-[UIApplication sharedApplication].statusBarFrame.size.height/2;
            _bottomView.y =viewY;
        }
        _bottomView.backgroundColor = [UIColor appColor];
        NSArray *titleArray = @[NSLocalizedString(@"Push", nil),NSLocalizedString(@"收藏并推送", nil)];
        for (int i = 0; i < 2; i++) {
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame = CGRectMake(KSCREENWIDTH/2 * i, 0, KSCREENWIDTH/2, 44);
            btn.tag = 100+i;
            [btn setTitle:titleArray[i] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            btn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
            [btn addTarget:self action:@selector(buyAndPush:) forControlEvents:UIControlEventTouchUpInside];
            [_bottomView addSubview:btn];
        }
        
        UIView *lineView = [[UIView alloc]init];
        lineView.frame =CGRectMake(KSCREENWIDTH/2 - 0.25, 10, 0.5, 24);
        lineView.backgroundColor = [UIColor whiteColor];
        [_bottomView addSubview:lineView];
    }
    return _bottomView;
}
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        if (self.type == IGPushiGalleryType1N || self.type == IGPushiGalleryType1NTpush || self.type == IGPushiGalleryTypeLIST) {
            _tableView.tableHeaderView = self.headerView;
        } else {
            _tableView.tableHeaderView = self.collectionView;
        }
        
        _tableView.separatorColor = [UIColor c6Color];
    }
    return _tableView;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.sectionInset = UIEdgeInsetsMake(6, 6, 6, 6);
        flowLayout.minimumLineSpacing = 6;
        flowLayout.minimumInteritemSpacing = 6;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, self.recommendArr.count<=4?(KSCREENWIDTH - 30)/4+12:(KSCREENWIDTH - 30)/2+18) collectionViewLayout:flowLayout];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.scrollEnabled = NO;
        //        _collectionView.alwaysBounceVertical = YES;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[IGIssueImageCell class] forCellWithReuseIdentifier:issueImageCellIdentifier];
        
    }
    return _collectionView;
}

- (UIView *)headerView {
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 125)];
        
        UIImageView *imgView = [[UIImageView alloc] init];
        _headerView.backgroundColor = [UIColor mainBackgroundColor];
        [_headerView addSubview:imgView];
//        [imgView sd_setImageWithURL:[NSURL URLWithString:self.recommend.image]];
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.font = [UIFont boldSystemFontOfSize:16.0];
        titleLabel.textColor = [UIColor c4Color];
        [_headerView addSubview:titleLabel];
//        titleLabel.text = self.recommend.title;
        
        UILabel *authorLabel = [[UILabel alloc] init];
        authorLabel.font = [UIFont font14];
        authorLabel.textColor = [UIColor c5Color];
        [_headerView addSubview:authorLabel];
//        authorLabel.text = self.recommend.uploader;
        
        if (self.type == IGPushiGalleryTypeLIST) {
            [imgView sd_setImageWithURL:[NSURL URLWithString:self.pictureListModel.image]];
            titleLabel.text = self.pictureListModel.title;
            authorLabel.text = self.pictureListModel.userName;
        } else {
            [imgView sd_setImageWithURL:[NSURL URLWithString:self.recommend.image]];
            titleLabel.text = self.recommend.title;
            authorLabel.text = self.recommend.uploader;
        }
        
        
        
        [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(kGAP15);
            make.width.height.mas_equalTo(90);
//            make.centerY.mas_equalTo(_headerView.mas_centerY);
            make.top.mas_equalTo(kGAP18);
            
        }];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(imgView.mas_right).offset(kGAP17);
            make.top.mas_equalTo(imgView.mas_top).offset(kGAP24);
            make.right.mas_equalTo(-5);
            make.height.mas_equalTo(20);
        }];
        
        [authorLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(imgView.mas_right).offset(kGAP17);
            make.top.mas_equalTo(titleLabel.mas_bottom).offset(kGAP11);
            make.right.mas_equalTo(-5);
            make.height.mas_equalTo(20);
        }];
    }
    return _headerView;
}

-(NSMutableString *)deviceIds{
    if (!_deviceIds) {
        _deviceIds = [[NSMutableString alloc]init];
    }
    return _deviceIds;
}

-(NSMutableString *)pIds{
    if (!_pIds) {
        _pIds = [[NSMutableString alloc]init];
    }
    return _pIds;
}

-(NSString *)unPurchaseId{
    if (!_unPurchaseId) {
        _unPurchaseId = [[NSString alloc]init];
    }
    return _unPurchaseId;
}

#pragma mark -help
/*
 画单都需要遍历，判断是否已经收藏（购买），画作只需判断一次即可
 1.1. 都收藏了                              直接推送
 1.2. 未收藏 & 作品金额==0                   先收藏后推送（不进入购买界面）
 1.3. 有未收藏的作品 & 金额！=0               进入购买支付界面，支付成功后，直接执行推送操作，然后返回到当前推送界面
 失败，也返回到当前推送界面
 2.1. 画单 & 包含未收藏的画作 点击推送时        提示  请先收藏画单
 */
-(void)buyAndPush:(UIButton *)btn{
    NSLog(@"%zd",btn.tag);
    
    __weak typeof(self) weakSelf = self;
    NSMutableArray *tmpArr = [NSMutableArray array];
    for (IGiGalleryEqu *equ in self.iGalleryListArr) {
        if (equ.isSelected) {
            [tmpArr addObject:equ.macId];
        }
    }
    if (tmpArr.count == 0) {
        //        [self presentMessageTips:@"请选择设备"];
        [self presentMessageTips:NSLocalizedString(@"Please Select Device", nil)];
        return;
    }

    
    
    
    IGPicturePushApi *pushApi = [[IGPicturePushApi alloc]init];
    
    pushApi.isTPush = (self.type == IGPushiGalleryType1NTpush?@"1":@"0");
    
    NSMutableArray *pidsArray = [NSMutableArray array];
    if (self.type == IGPushiGalleryTypeNN) {
        if ([self.source integerValue]==1) {
            for (IGAtlasDetailModel *work in self.recommendArr) {
                NSString *aId = work.pid;
                [pidsArray addObject:aId];
            }
        }else{
            for (IGArtWorkModel *work in self.recommendArr) {
                NSString *aId = work.aId;
                [pidsArray addObject:aId];
            }
        }
        pushApi.pType = @"0";//画作推送
    } else if (self.type == IGPushiGalleryTypeLIST){
//        pidsArray addObject:self.pictureListModel.id
        pushApi.pType = @"1";//画单推送
        [pidsArray addObject:self.pictureListModel.drawlistId];
    } else {
        if ([self.source integerValue]==1) {
            [pidsArray addObject:self.atlastRecommend.pid];
        }else{
            [pidsArray addObject:self.recommend.aId];
        }
        pushApi.pType = @"0";//画作推送
    }

    
    
    pushApi.macIds = [tmpArr componentsJoinedByString:@","];
    pushApi.pIds = [pidsArray componentsJoinedByString:@","];

    
    
    if (pushApi.isTPush) {
        pushApi.text = self.pushText;
    }
    
    
    NSString * isMyandPush = [[NSString alloc]init];
    if (btn.tag == 100) {
        //推送
        isMyandPush = @"0";
        
    } else if (btn.tag == 101){
        //收藏并推送
        isMyandPush = @"1";
    }
    pushApi.isPurchase = isMyandPush;
    
    
    if (btn.tag == 100) {
        //推送
        [self presentMessageTips:NSLocalizedString(@"Pushing...", nil)];
        [pushApi startWithDecodeClass:[IGPicturePushResponse class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
            if (responseObject) {
                IGPicturePushResponse *response = responseObject;
                IGBaseRespHead *head = response.resHeader;
                IGPicturePushModel *model = response.data;
                if ([head.code isEqualToString:@"success"]) {
                    [self presentMessageTips:NSLocalizedString(@"Pushed Successfully...\n Would show up until device online.", nil)];
                    NSString *inputString = @"1";
                    if (weakSelf.successBlock) {
                        //将自己的值传出去，完成传值
                        weakSelf.successBlock(inputString);
                    }
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                } else {
                    if (self.type == IGPushiGalleryTypeLIST) {
                        [weakSelf presentMessageTips:@"请先收藏画单"];
                    } else if (self.type == IGPushiGalleryTypeNN){
                        [weakSelf presentMessageTips:@"您有未收藏作品,请收藏后推送"];
                    }
//                    [weakSelf presentMessageTips:head.message];
                    weakSelf.unPurchaseId = model.unPurchasedId;
                }
            }
        }];
    } else if (btn.tag == 101){
        //收藏并推送
        
        //       (1)都所有作品的收藏过了,直接推送
        //       (1)未收藏的作品金额加起来是0,不进入购买界面,直接自动收藏,后推送
        //       (1)未收藏作品金额加起来不是0,直接进入购买支付界面
        //          (1)支付成功，直接执行推送操作，然后返回到当前推送界面
        //          (1)支付失败，也返回当前推送界面
        [pushApi startWithDecodeClass:[IGPicturePushResponse class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
            if (responseObject) {
                IGPicturePushResponse *response = responseObject;
                IGBaseRespHead *head = response.resHeader;
                IGPicturePushModel *model = response.data;
                if ([head.code isEqualToString:@"success"]) {
                    [self presentMessageTips:NSLocalizedString(@"Pushed Successfully...\n Would show up until device online.", nil)];
                    NSString *inputString = @"1";
                    if (weakSelf.successBlock) {
                        //将自己的值传出去，完成传值
                        weakSelf.successBlock(inputString);
                    }
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                } else {
                    if (self.type == IGPushiGalleryTypeLIST) {
                        [weakSelf presentMessageTips:@"请先收藏画单"];
                    } else if (self.type == IGPushiGalleryTypeNN){
                        [weakSelf presentMessageTips:@"您有未收藏作品,请收藏后推送"];
                    }
                    //                    [weakSelf presentMessageTips:head.message];
                    weakSelf.unPurchaseId = model.unPurchasedId;
                    IGMultipleDrawingsBuyVC *vc =[[IGMultipleDrawingsBuyVC alloc]init];
                    vc.type =( pushApi.pType==0)?@"2":@"1";
                    vc.thingId = model.unPurchasedId;
                    [UIViewController ig_pushViewController:vc animated:YES];
                }
            }
        }];
    }
    
    /*
    NSMutableArray *worksArr = [NSMutableArray array];
    if (self.type == IGPushiGalleryTypeNN) {
        if ([self.source integerValue]==1) {
            for (IGAtlasDetailModel *work in self.recommendArr) {
                NSString *aId = work.pid;
                [worksArr addObject:aId];
            }
        }else{
            for (IGArtWorkModel *work in self.recommendArr) {
                NSString *aId = work.aId;
                [worksArr addObject:aId];
            }
        }
    } else {
        if ([self.source integerValue]==1) {
            [worksArr addObject:self.atlastRecommend.pid];
        }else{
            [worksArr addObject:self.recommend.aId];
        }
    }
    IGiGalleryPushApi *pushApi = [[IGiGalleryPushApi alloc] initWithMacIds:tmpArr pIds:worksArr];
    if (self.type == IGPushiGalleryType1NTpush) {
        pushApi.isTPush = @"1";
        pushApi.text = self.pushText;
    }
    //    [self presentMessageTips:@"正在推送..."];
    [self presentMessageTips:NSLocalizedString(@"Pushing...", nil)];
    [pushApi startWithDecodeClass:[IGiGalleryPushResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            //            [self presentMessageTips:@"推送成功"];
            [self presentMessageTips:NSLocalizedString(@"Pushed Successfully...\n Would show up until device online.", nil)];
            NSString *inputString = @"1";
            if (weakSelf.successBlock) {
                //将自己的值传出去，完成传值
                weakSelf.successBlock(inputString);
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
    
    
    
    */
    
    
    
    
    
}

//选择 & 取消  所有设备
-(void)selectAllDevice{
    _isAllDeviceSelected = !_isAllDeviceSelected;
    for (int i = 0; i < self.iGalleryListArr.count; i++) {
        IGiGalleryEqu *equ = self.iGalleryListArr[i];
        equ.isSelected = _isAllDeviceSelected;
    }
    [self.allSelectedImageV layoutIfNeeded];
    [self.tableView reloadData];
}


//选择 & 取消 单个设备
- (void)selButClick:(NSIndexPath *)indexPath {
    IGiGalleryEqu *equ = self.iGalleryListArr[indexPath.row];
    equ.isSelected = !(equ.isSelected);
    
    [self.tableView reloadData];
    
    BOOL selectAll = YES;
    for (IGiGalleryEqu *equ in self.iGalleryListArr) {
        if (!equ.isSelected) {
            selectAll = NO;
            break;
        }
    }
//    UIButton *button = (UIButton *)[self.view viewWithTag:100];
//    button.selected = selectAll;
    if (selectAll != _isAllDeviceSelected) {
        _isAllDeviceSelected = !_isAllDeviceSelected;
        [self.allSelectedImageV layoutIfNeeded];
    }
}

//原有逻辑中的bottom全选按钮
- (void)selButtonClicked:(UIButton *)sender {
    sender.selected = !(sender.selected);
    for (int i = 0; i < self.iGalleryListArr.count; i++) {
        IGiGalleryEqu *equ = self.iGalleryListArr[i];
        equ.isSelected = sender.selected;
    }
    
    [self.tableView reloadData];
}

/*
 画单都需要遍历，判断是否已经收藏（购买），画作只需判断一次即可
1.1. 都收藏了                              直接推送
1.2. 未收藏 & 作品金额==0                   先收藏后推送（不进入购买界面）
1.3. 有未收藏的作品 & 金额！=0               进入购买支付界面，支付成功后，直接执行推送操作，然后返回到当前推送界面
                                                     失败，也返回到当前推送界面
2.1. 画单 & 包含未收藏的画作 点击推送时        提示  请先收藏画单
*/
//原有逻辑中的推送逻辑
- (void)pushButtonClicked:(UIButton *)sender {
      __weak typeof(self) weakself = self;
    NSMutableArray *tmpArr = [NSMutableArray array];
    for (IGiGalleryEqu *equ in self.iGalleryListArr) {
        if (equ.isSelected) {
            [tmpArr addObject:equ.macId];
        }
    }
    if (tmpArr.count == 0) {
//        [self presentMessageTips:@"请选择设备"];
        [self presentMessageTips:NSLocalizedString(@"Please Select Device", nil)];
        return;
    }
    
    NSMutableArray *worksArr = [NSMutableArray array];
    if (self.type == IGPushiGalleryTypeNN) {
        if ([self.source integerValue]==1) {
            for (IGAtlasDetailModel *work in self.recommendArr) {
                NSString *aId = work.pid;
                [worksArr addObject:aId];
            }
        }else{
        for (IGArtWorkModel *work in self.recommendArr) {
            NSString *aId = work.aId;
            [worksArr addObject:aId];
        }
    }
    } else {
         if ([self.source integerValue]==1) {
             [worksArr addObject:self.atlastRecommend.pid];
         }else{
             [worksArr addObject:self.recommend.aId];
         }
    }
    IGiGalleryPushApi *pushApi = [[IGiGalleryPushApi alloc] initWithMacIds:tmpArr pIds:worksArr];
    if (self.type == IGPushiGalleryType1NTpush) {
        pushApi.isTPush = @"1";
        pushApi.text = self.pushText;
    }
//    [self presentMessageTips:@"正在推送..."];
    [self presentMessageTips:NSLocalizedString(@"Pushing...", nil)];
    [pushApi startWithDecodeClass:[IGiGalleryPushResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
//            [self presentMessageTips:@"推送成功"];
            [self presentMessageTips:NSLocalizedString(@"Pushed Successfully...\n Would show up until device online.", nil)];
            NSString *inputString = @"1";
            if (weakself.successBlock) {
                //将自己的值传出去，完成传值
                weakself.successBlock(inputString);
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}
    
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
